import React, {Component, createRef, RefObject} from 'react'
import {Button, Card, Form, Input, message, Spin} from "antd";
import {Store, ValidateErrorEntity} from 'rc-field-form/lib/interface'
import {FormInstance} from "antd/lib/form";
import ArticleInfo from "../../../types/ArticleInfo";
import {addArticle} from "../../../requests/article";
import ArticleType from "../../../types/ArticleType"
import wangeditor from 'wangeditor';
import './editor.less'
import {getRes} from "../../../configFile";

interface IProps {
    articleType: ArticleType
}
interface IState {
    articleInfo: ArticleInfo,
    isLoading: boolean,
}

export default class AddArticleComponent extends Component<IProps, IState> {
    formRef = React.createRef<FormInstance>()
    editorRef: RefObject<HTMLDivElement> = createRef()

    //编辑器实例声明 再didmount后操作DOM
    editor: any

    //初始化富文本编辑器
    initEditor = () => {
        this.editor = new wangeditor(this.editorRef.current)
        this.editor.customConfig.onchange = (htmlContent: string) => {
            if (this.formRef.current)
                this.formRef.current.setFieldsValue({ 'content': htmlContent })
        }
        this.editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
        this.editor.create()
    }

    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: true,
            articleInfo: {
                articleID: -1,
                articleType: this.props.articleType,
                title: '',
                authorID: -1,
                creationTimestamp: -1,
                lastModifiedTimestamp: -1,
                picturePath: '',
                content: ''
            }
        }
    }

    layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };
    tailLayout = {
        wrapperCol: { offset: 4 },
    };

    async componentDidMount() {
        this.initEditor()       //操作DOM初始化editor
        this.setState({
            ...this.state,
            isLoading: false
        })
    }


    //输入合法函数
    onFinish: (values: Store) => void = async values => {
        console.log(values)
        try {
            this.setState({ isLoading: true })
            const res = getRes(await addArticle(this.props.articleType, values.title, values.content))
            if (res.isSuccessful) {
                message.success("添加成功")
                //清空
                this.formRef.current?.resetFields(['title']);
                this.editor.txt.clear();
            } else {
                message.error("添加失败")
            }
        } catch (err) {
            message.error(err.toString())
        }finally {
            this.setState({ isLoading: false })
        }
    }

    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };


    render() {
        return (
            <div>
                <Spin size='large' spinning={this.state.isLoading}>
                    <Card
                        title={<span style={{ fontWeight: 'bold' }}>添加 {this.props.articleType === 'EVALUATION' ? '测评文章' : '设备知识'}</span>}
                        bordered={true}>
                        <Form
                            onFinishFailed={this.onFinishFailed}
                            onFinish={this.onFinish}
                            ref={this.formRef}
                            {...this.layout}
                            name="addArticle"
                        >

                            <Form.Item
                                label="文章标题"
                                name="title"
                                rules={[{ required: true }]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="文章内容"
                                name="content"
                                rules={[{ required: true }]}
                            >
                                <div className="editorDiv" ref={this.editorRef} />
                            </Form.Item>


                            <Form.Item {...this.tailLayout}>
                                <Button type="primary" htmlType="submit" size="large">
                                    确认添加
                                </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                </Spin>
            </div>
        )
    }
}
